package com.atghost.minio.config.websocket;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Admin
 * @version 1.0
 * @date 2024-5-10 22:05
 **/
@Component
@ServerEndpoint("/imserver/{token}")
public class WebSocketService {

    private final Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    /**
     * 连接人数
     **/
    public static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * 存放所有客户端的连接
     **/
    public static final Map<String, WebSocketService> WEBSOCKET_MAP = new ConcurrentHashMap<>();
    /**
     * 服务端和客户端的会话
     **/
    private Session session;
    /**
     * 服务端和客户端的会话id
     **/
    public String sessionId;

    private Long userId;

    private static ApplicationContext APPLICATIONCONTEXT;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketService.APPLICATIONCONTEXT = applicationContext;
    }


    /**
     * 连接成功调用
     **/
    @OnOpen
    public void openConnection(Session session, @PathParam("token") String token) {
        System.out.println("连接成功调用");
        sessionId = session.getId();
        this.session = session;
        if (WEBSOCKET_MAP.containsKey(sessionId)) {
            WEBSOCKET_MAP.remove(sessionId);
        } else {
            //在线人数加一
            ONLINE_COUNT.getAndIncrement();
        }
        WEBSOCKET_MAP.put(sessionId, this);
        logger.info("用户连接成功:" + sessionId + ",当前在线人数:" + ONLINE_COUNT.get());

        try {
            this.sendMessage("0");
        } catch (Exception e) {
            logger.error("连接异常");
        }
    }

    /**
     * 断开连接
     **/
    @OnClose
    public void closeConnection() {
        System.out.println("断开连接");
        if (WEBSOCKET_MAP.containsKey(sessionId)) {
            WEBSOCKET_MAP.remove(sessionId);
            ONLINE_COUNT.getAndDecrement();
        }
        logger.info("用户退出:" + sessionId + ",当前在线人数:" + ONLINE_COUNT.get());
    }

    /**
     * 收到前端的消息
     **/
    @OnMessage
    public void onMessage(String message) {
        logger.info("用户信息:" + sessionId + ",报文:" + message);
        if (StringUtils.isNotBlank(message)) {
            try {
                //群发消息
                for (Map.Entry<String, WebSocketService> entry : WEBSOCKET_MAP.entrySet()) {
                    WebSocketService webSocketService = entry.getValue();


                }




            } catch (Exception e) {
                logger.error("弹幕接收出现问题");
                e.printStackTrace();
            }
        }

    }

    /**
     * 异常
     **/
    @OnError
    public void onError(Throwable e) {
        System.out.println("异常");
    }

    /**
     * 发送消息
     **/
    public void sendMessage(String message) throws IOException {
        System.out.println("发送消息");
        this.session.getBasicRemote().sendText(message);
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }
}
